package com.jt.utils;

import com.jt.pojo.User;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    // 设置token过期时间
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    private static final String TOKEN_MIYAO = "asfhwkwewrkjwerwr";

    //生成 token
    public static String getToken(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", user.getName());
        map.put("passworld", user.getPassWold());
        JwtBuilder builder = Jwts.builder();
        builder.setExpiration(new Date(System.currentTimeMillis() + EXPIRE));
            builder.addClaims(map);
        builder.signWith(SignatureAlgorithm.HS256, TOKEN_MIYAO);
        return builder.compact();
    }

    /*解析TOKEN*/
    public static Map<String, Object> JieXi(String token) {
        Jwt parse = Jwts.parser().setSigningKey(TOKEN_MIYAO).parse(token);
        Map<String, Object> body = (Map<String, Object>) parse.getBody();
        return body;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setName("刘蜀鸿");
        user.setPassWold("123456789");
        String token = JwtUtils.getToken(user);
        System.out.println(token);
        Map<String, Object> map = JwtUtils.JieXi(token);
        System.out.println(map);
    }
}
